<template>
  <div class="page-container">
    <h2>套餐管理</h2>
    
    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="套餐名称">
        <el-input v-model="searchForm.menuName" placeholder="请输入套餐名称" clearable />
      </el-form-item>
      <el-form-item label="价格范围">
        <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价格" />
        <span style="margin: 0 10px">-</span>
        <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价格" />
      </el-form-item>
      <el-form-item label="套餐状态">
        <el-select v-model="searchForm.menuState" placeholder="请选择套餐状态" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增套餐
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table 
      :data="displayedData" 
      v-loading="loading"
      class="table-container"
      border
      stripe
    >
      <template #empty>
        <div style="padding: 24px; color: #909399;">暂无数据</div>
      </template>
      <el-table-column prop="menuId" label="套餐ID" width="80" />
      <el-table-column prop="menuName" label="套餐名称" min-width="200" />
      <el-table-column prop="beforePrice" label="原价" width="120">
        <template #default="{ row }">
          <span style="color: #909399;">
            ¥{{ row.beforePrice?.toFixed(2) || '0.00' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="afterPrice" label="套餐价格" width="120">
        <template #default="{ row }">
          <span style="color: #f56c6c; font-weight: bold;">
            ¥{{ row.afterPrice?.toFixed(2) || '0.00' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="menuShop" label="套餐店铺" width="120">
        <template #default="{ row }">
          <el-tag type="info">{{ getMenuShopText(row.menuShop) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="menuState" label="套餐状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.menuState === 1 ? 'success' : 'danger'">
            {{ row.menuState === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="套餐名称" prop="menuName">
          <el-input 
            v-model="formData.menuName" 
            placeholder="请输入套餐名称" 
          />
        </el-form-item>
        <el-form-item label="原价" prop="beforePrice">
          <el-input-number 
            v-model="formData.beforePrice" 
            :min="0" 
            :precision="2"
            placeholder="请输入原价"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="套餐价格" prop="afterPrice">
          <el-input-number 
            v-model="formData.afterPrice" 
            :min="0" 
            :precision="2"
            placeholder="请输入套餐价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="套餐店铺" prop="menuShop">
          <el-select v-model="formData.menuShop" placeholder="请选择套餐店铺">
            <el-option label="总店" :value="1" />
            <el-option label="分店1" :value="2" />
            <el-option label="分店2" :value="3" />
            <el-option label="线上店铺" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="套餐状态" prop="menuState">
          <el-radio-group v-model="formData.menuState">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { menuApi } from '@/api/menu'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  menuName: '',
  minPrice: null,
  maxPrice: null,
  menuState: null
})

// 表格数据
const tableData = ref([])

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 过滤后的数据
const filteredData = computed(() => {
  return (tableData.value || []).filter(item => {
    const matchName = !searchForm.menuName || (item.menuName || '').includes(searchForm.menuName)
    const matchState = (searchForm.menuState === null || searchForm.menuState === undefined) || item.menuState === searchForm.menuState
    const matchMin = (searchForm.minPrice === null || searchForm.minPrice === undefined) || (Number(item.afterPrice) >= Number(searchForm.minPrice))
    const matchMax = (searchForm.maxPrice === null || searchForm.maxPrice === undefined) || (Number(item.afterPrice) <= Number(searchForm.maxPrice))
    return matchName && matchState && matchMin && matchMax
  })
})

// 当前页展示数据
const displayedData = computed(() => {
  pagination.total = filteredData.value.length
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 表单数据
const formData = reactive({
  menuId: null,
  menuName: '',
  beforePrice: 0,
  afterPrice: 0,
  menuShop: 1,
  menuState: 1,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const formRules = {
  menuName: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' }
  ],
  beforePrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0, message: '原价不能小于0', trigger: 'blur' }
  ],
  afterPrice: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '套餐价格不能小于0', trigger: 'blur' }
  ],
  menuShop: [
    { required: true, message: '请选择套餐店铺', trigger: 'change' }
  ],
  menuState: [
    { required: true, message: '请选择套餐状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取套餐店铺文本
const getMenuShopText = (shop) => {
  const shopMap = {
    1: '总店',
    2: '分店1',
    3: '分店2',
    4: '线上店铺'
  }
  return shopMap[shop] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取套餐列表
const getMenuList = async () => {
  try {
    loading.value = true
    const response = await menuApi.getMenuList(searchForm)
    tableData.value = response.data || []
  } catch (error) {
    ElMessage.error('获取套餐列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getMenuList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    menuName: '',
    minPrice: null,
    maxPrice: null,
    menuState: null
  })
  getMenuList()
}

// 新增套餐
const handleAdd = () => {
  dialogTitle.value = '新增套餐'
  resetFormData()
  dialogVisible.value = true
}

// 编辑套餐
const handleEdit = (row) => {
  dialogTitle.value = '编辑套餐'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除套餐
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该套餐吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await menuApi.deleteMenu(row.menuId)
    ElMessage.success('删除成功')
    getMenuList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (formData.menuId) {
      await menuApi.updateMenu(formData)
      ElMessage.success('修改成功')
    } else {
      await menuApi.addMenu(formData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getMenuList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(formData.menuId ? '修改失败' : '添加失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    menuId: null,
    menuName: '',
    beforePrice: 0,
    afterPrice: 0,
    menuShop: 1,
    menuState: 1,
    startTime: '',
    endTime: ''
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
}

// 初始化
onMounted(() => {
  getMenuList()
})
</script>

<style scoped>
.search-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
